//
//  ChangeUserMessageViewController.m
//  AllFamily
//
//  Created by chirui on 2018/5/25.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "ChangeUserMessageViewController.h"
#import "RegionPicker.h"
#import "applyVipViewController.h"

@interface ChangeUserMessageViewController ()<UIPickerViewDataSource, UIPickerViewDelegate>{
    
    NSString * chooseUserPhoto;
    NSString * chooseFontPhtot;
    NSString * chooseBackPhoto;
    NSString * chooseStr;

    
    NSData * UserPhotoData;
    NSData * FontPhtotData;
    NSData * BackPhotoData;
    
    NSMutableArray * imageDataArray;
    NSMutableArray * imagetitleArray;
    
    
    
}
@property (weak, nonatomic) IBOutlet UIButton *userImageBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameText;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UIButton *fontImageBtn;
@property (weak, nonatomic) IBOutlet UIButton *backImageBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet UITextField *cardNumberText;



@property(nonatomic, strong) RegionPicker *pickerView;
@property(nonatomic, strong) NSString *selectedRegion;
@property(nonatomic, strong) NSArray * province;  //区域-省份
@property(nonatomic, strong) NSArray *city;  //区域-城市
@property(nonatomic, strong) NSArray *country;  //区域-乡镇、街道
@property(nonatomic, strong) NSString *mem_province;
@property(nonatomic, strong) NSString *mem_city;
@property(nonatomic, strong) NSString *mem_country;




@end

@implementation ChangeUserMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
      chooseUserPhoto = @"0";
      chooseFontPhtot = @"0";
      chooseBackPhoto = @"0";
      chooseStr = @"0";
    
    
    imageDataArray = @[].mutableCopy;
    imagetitleArray = @[].mutableCopy;
   
    TitleView(@"个人信息");

    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    self.userImageBtn.layer.cornerRadius = 25.f;
    self.userImageBtn.layer.masksToBounds = YES;
    
    self.sureBtn.layer.cornerRadius = 3.f;
    self.sureBtn.layer.masksToBounds = YES;
    
    NSString * path = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *fileData = [NSData dataWithContentsOfFile:path];

    self.province = [NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:nil];
    
    if (self.dataDic) {
        
        [_userImageBtn sd_setBackgroundImageWithURL:ImageUrl(self.dataDic[@"header"]) forState:UIControlStateNormal placeholderImage:ImageName(@"icon_user_head _portrait_1")];
        _nameText.text = self.dataDic[@"nickname"];
        _cardNumberText.text = self.dataDic[@"id_card_num"];
        _addressLabel.text = [NSString stringWithFormat:@"%@%@%@",self.dataDic[@"province"],self.dataDic[@"city"],self.dataDic[@"county"]];
        chooseStr = @"1";
     
        self.mem_province = self.dataDic[@"province"];
        self.mem_city = self.dataDic[@"city"];
        self.mem_country = self.dataDic[@"county"];
        
        [_fontImageBtn sd_setBackgroundImageWithURL:ImageUrl(self.dataDic[@"card_front"]) forState:UIControlStateNormal placeholderImage:ImageName(@"positive")];
        
           [_backImageBtn sd_setBackgroundImageWithURL:ImageUrl(self.dataDic[@"card_back"]) forState:UIControlStateNormal placeholderImage:ImageName(@"opposite")];
    }
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithTitle:@"申请等级" target:self action:@selector(applyBtnClick)];
    
       self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
    
    // picker
    self.pickerView = [[RegionPicker alloc]initWithFrame:CGRectMake(0, 0, screenW, screenH-64)];
    self.pickerView.pickerView.dataSource = self;
    self.pickerView.pickerView.delegate = self;
    [self.pickerView.confirmButton addTarget:self action:@selector(regionSelectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.pickerView setHidden:YES];
    [self.view addSubview:self.pickerView];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)applyBtnClick{
    
    applyVipViewController * apply = [[applyVipViewController alloc]init];
    [self.navigationController pushViewController:apply animated:YES];
}

- (IBAction)userImageClick:(UIButton *)sender {
    if([[UIResponder currentFirstResponder] isKindOfClass:[UITextField class]]) {
        [[UIResponder currentFirstResponder] resignFirstResponder];
    }
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            chooseUserPhoto = @"1";
            UserPhotoData  = UIImageJPEGRepresentation(image, 0.5);
            [_userImageBtn setBackgroundImage:image forState:UIControlStateNormal];
        }
    }];
}

- (IBAction)chosseAddressClick:(UIButton *)sender {
    //所在区域
    if([[UIResponder currentFirstResponder] isKindOfClass:[UITextField class]]) {
        [[UIResponder currentFirstResponder] resignFirstResponder];
    }
    
    if(!self.province) {
        
        NSString * path = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
        NSData *fileData = [NSData dataWithContentsOfFile:path];
        
        self.province = [NSJSONSerialization JSONObjectWithData:fileData options:NSJSONReadingMutableLeaves error:nil];
        
        self.city = self.province[0][@"sub"];
        self.country = self.city[0][@"sub"];
        self.mem_province = self.province[0][@"area"];
        self.mem_city = self.city[0][@"area"];
        self.mem_country = self.country[0][@"area"];
        self.selectedRegion = [NSString stringWithFormat:@"%@%@%@",self.province[0][@"area"], self.city[0][@"area"], self.country[0][@"area"]];
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }else {
        [self.pickerView setHidden:NO];
        [self.pickerView.pickerView reloadAllComponents];
    }
    
}
- (IBAction)fontClick:(UIButton *)sender {
    if([[UIResponder currentFirstResponder] isKindOfClass:[UITextField class]]) {
        [[UIResponder currentFirstResponder] resignFirstResponder];
    }
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
             chooseFontPhtot = @"1";
             FontPhtotData  = UIImageJPEGRepresentation(image, 0.5);
            [_fontImageBtn setBackgroundImage:image forState:UIControlStateNormal];
        }
    }];
}
- (IBAction)backClick:(UIButton *)sender {
    if([[UIResponder currentFirstResponder] isKindOfClass:[UITextField class]]) {
        [[UIResponder currentFirstResponder] resignFirstResponder];
    }
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            chooseBackPhoto = @"1";
            BackPhotoData  = UIImageJPEGRepresentation(image, 0.5);
            [_backImageBtn setBackgroundImage:image forState:UIControlStateNormal];
        }
    }];
    
}
- (IBAction)sureBtnClick:(UIButton *)sender {
    
    if (_nameText.text.length<=0||_nameText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入姓名");
        return;
    }
    if (_cardNumberText.text.length<=0||_cardNumberText.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入身份证号");
        return;
    }
    if (_mem_province.length<=0||_mem_city.length<=0||_mem_country.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请选择地址");
        return;
    }
    
    if ([chooseUserPhoto isEqualToString:@"1"]||[chooseFontPhtot isEqualToString:@"1"]||[chooseBackPhoto isEqualToString:@"1"]) {
        
        [self upIconImageRequest];
    }else {
        
        [self changeMessageRequest];
    }
    
}
// 有头像跟名称的
-(void)upIconImageRequest{
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"nickname":_nameText.text,
                           @"id_card_num":_cardNumberText.text,
                           @"province":self.mem_province,
                           @"city":self.mem_city,
                           @"county":self.mem_country
                           };
    
    if (imagetitleArray) {
        [imagetitleArray removeAllObjects];
    }
    if (imageDataArray) {
        [imageDataArray removeAllObjects];
    }
    
    if ([chooseUserPhoto isEqualToString:@"1"]) {
        [imagetitleArray  addObject:@"header"];
        [imageDataArray addObject:UserPhotoData];
    }
    
    if ([chooseFontPhtot isEqualToString:@"1"]) {
        [imagetitleArray  addObject:@"card_front"];
        [imageDataArray addObject:FontPhtotData];
    }
    
    if ([chooseBackPhoto isEqualToString:@"1"]) {
        [imagetitleArray  addObject:@"card_back"];
        [imageDataArray addObject:BackPhotoData];
    }
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:RequestUrlStr(modify_userInfo_api) parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        for (int i = 0; i<imagetitleArray.count; i++) {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
            [formData appendPartWithFileData:imageDataArray[i] name:imagetitleArray[i] fileName:fileName mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    } ];
    
}

// 没有图片的
-(void)changeMessageRequest {
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"nickname":_nameText.text,
                           @"id_card_num":_cardNumberText.text,
                           @"province":self.mem_province,
                           @"city":self.mem_city,
                           @"county":self.mem_country
                           };
    SHuiMBhubNoTimeStr(@"正在提交...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(modify_userInfo_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]== 200) {
            
            SHuiMBhudTextTimeStr(@"提交成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
            
        }else{
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
    
}

#pragma mark - UIPickerView datasource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            if(![self.province isKindOfClass:[NSNull class]]) {
                return self.province.count;
            }else {
                return 0;
            }
        }
            break;
        case 1:
        {
            if(![self.city isKindOfClass:[NSNull class]]) {
                return self.city.count;
            }else {
                return 0;
            }
        }
            break;
        case 2:
        {
            if(![self.country isKindOfClass:[NSNull class]]) {
                return self.country.count;
            }else {
                return 0;
            }
        }
            break;
        default:
            break;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (component) {
            
        case 0:
        {
            // 省份
            return self.province[row][@"area"];
        }
            break;
        case 1:
        {
            // 城市
            return self.city[row][@"area"];
        }
            break;
        case 2:
        {
            // 乡镇、街道
            return self.country[row][@"area"];
        }
            break;
        default:
            break;
    }
    return nil;
}

#pragma mark - UIPickerView delegate
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (component) {
        case 0:
        {
            // 省份
            self.city = self.province[row][@"sub"];
            self.country = self.city[0][@"sub"];
            [pickerView selectRow:0 inComponent:1 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:1];
        }
            break;
        case 1:
        {
            // 城市
            self.country = self.city[row][@"sub"];
            [pickerView selectRow:0 inComponent:2 animated:NO];
            [self pickerView:self.pickerView.pickerView didSelectRow:0 inComponent:2];
        }
            break;
        case 2:
        {
            // 乡镇、街道
        }
            break;
        default:
            break;
    }
    
    
    self.mem_province = self.province[[pickerView selectedRowInComponent:0]][@"area"];
    self.selectedRegion = self.province[[pickerView selectedRowInComponent:0]][@"area"];
    
    self.mem_city = self.city[[pickerView selectedRowInComponent:1]][@"area"];
    self.selectedRegion = [self.selectedRegion stringByAppendingString:self.city[[pickerView selectedRowInComponent:1]][@"area"]];
    
    if([self.country isKindOfClass:[NSArray class]]) {
        self.mem_country = self.country[[pickerView selectedRowInComponent:2]][@"area"];
        self.selectedRegion = [self.selectedRegion stringByAppendingString:self.country[[pickerView selectedRowInComponent:2]][@"area"]];
    }else {
        self.mem_country = self.city[[pickerView selectedRowInComponent:1]][@"area"];;
    }
    
    [pickerView reloadAllComponents];
}

// 区域选择确定
- (void)regionSelectAction {
    [self.pickerView setHidden:YES];
    chooseStr = @"1";
    self.addressLabel.text = self.selectedRegion;
   
}




@end
